// 引入加密
const md5 = require("md5")
// 引入数据库
const {
  mysqlFun
} = require('../mysql/mysql');
exports.postLogin = function (app) {
  app.post("/login", (req, res) => {
    // 生成一个用户登录评论
    let userId = Math.floor(Math.random() * 1000000000);
    const sql = `select * from userdata where user = ${req.body.username}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      // 通过长度判断是否有返回数据
      if (data.length === 0) {
        res.json({
          code: 'A0000',
          data: '',
          msg: '未注册'
        })
        return;
      }
      // 判断用户密码是否正确
      if (data[0].password === md5(req.body.password)) {

        // 把登录凭证存入账号内
        let sqlId = `UPDATE userdata SET userid=${userId} WHERE user=${req.body.username}`;

        function obj(data) {
          if (data === undefined) {
            return;
          }
        }
        mysqlFun(sqlId, obj);

        res.json({
          code: 'A0002',
          msg: '登录成功',
          // 用户登录成功之后返回一个用户名一个id
          data: {
            user: data[0].user,
            id: data[0].id,
            qq: data[0].email.substring(0, data[0].email.indexOf('@')),
            userId: userId
          }
        })
        return;
      }
      res.json({
        code: 'A0001',
        data: '',
        msg: '密码错误'
      })
    }
    mysqlFun(sql, obj);
  })

  app.post("/loginCook", (req, res) => {
    const sql = `select * from userdata where user = ${req.body.username}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      // 判断用户凭证是否和账号存储凭证一致
      if (Number(data[0].userid) === Number(req.body.userid)) {
        res.json({
          code: 'L0001',
          msg: '凭证正确，自动登录成功',
          data: {
            id: data[0].id,
            qq: data[0].email.substring(0, data[0].email.indexOf('@'))
          }
        })
        return;
      }
      res.json({
        code: 'L0000',
        msg: '凭证错误,无法自动登录'
      })
    }
    mysqlFun(sql, obj);
  })
}